<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('Languages')"></page-header>
        <a-card :bordered="false">
          <!-- 操作部分 -->
          <a-row :gutter="8">
            <a-col :md="20" :sm="12">
              <a-button
                :type="'primary'"
                v-if="isGranted('Pages.Administration.Languages.Create')"
                @click="createOrEditLanguage()"
              >
                <plus-outlined />
                <span>{{ l('CreateNewLanguage') }}</span>
              </a-button>
              <a-button
                :type="'danger'"
                v-if="isGranted('Pages.Administration.Languages.Delete')"
                @click="batchDelete"
              >
                <delete-outlined />
                <span>{{ l('BatchDelete') }}</span>
              </a-button>
            </a-col>
          </a-row>

          <!-- 数据部分 -->
          <div class="my-md">
            <a-alert :type="'info'" :showIcon="true">
              <template #message>
                <span v-html="l('GridSelectedXItemsTips', selectedRowKeys.length)"></span>
                <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
                <a-divider type="vertical"></a-divider>
                <a @click="refresh()">{{ l('Refresh') }}</a>
              </template>
            </a-alert>
          </div>
        </a-card>
      </div>
      <!-- 表格 -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :pagination="false"
          :columns="columns"
          :data-source="dataList"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            checkAll: checkAll,
            getCheckboxProps: getCheckboxProps,
          }"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'displayName'">
              {{ record.displayName }}{{ record.name === defaultLanguageName ? '(默认)' : '' }}
            </template>
            <template v-if="column.key === 'name'">
              {{ record.name }}
            </template>
            <template v-if="column.key === 'creationTime'">
              {{ _moment(record.creationTime) }}
            </template>
            <template v-if="column.key === 'isDisabled'">
              <p class="isDisabled">
                <CheckCircleTwoTone v-if="!record.isDisabled" twoToneColor="#52c41a" />
                <CloseCircleTwoTone v-if="record.isDisabled" twoToneColor="#ff0000" />
              </p>
            </template>
            <template v-if="column.key === 'actions'">
              <!-- 修改 -->
              <a
                class="table-edit"
                @click="createOrEditLanguage(record)"
                v-if="
                  isGranted('Pages.Administration.Languages.Edit') &&
                  record.tenantId == tenantId &&
                  record.name !== 'zh-Hans' &&
                  record.name !== 'en'
                "
              >
                <edit-outlined />
                {{ l('Edit') }}
              </a>
              <!-- 删除 -->
              <a-popconfirm
                placement="top"
                v-if="
                  isGranted('Pages.Administration.Languages.Delete') &&
                  record.tenantId == tenantId &&
                  record.name !== 'zh-Hans' &&
                  record.name !== 'en'
                "
                :okText="l('Ok')"
                :cancelText="l('Cancel')"
                @confirm="deleteItem(record)"
              >
                <template #title>
                  {{ l('ConfirmDeleteWarningMessage') }}
                </template>
                <a class="table-delete">
                  <delete-outlined />
                  {{ l('Delete') }}
                </a>
              </a-popconfirm>
              <!-- 更多 -->
              <a-dropdown
                v-if="
                  isGrantedAny(
                    'Pages.Administration.Languages.ChangeTexts',
                    'Pages.Administration.Languages.Edit',
                  )
                "
              >
                <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
                  {{ l('Actions') }}
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="isGranted('Pages.Administration.Languages.ChangeTexts')"
                      @click="changeTexts(record)"
                    >
                      <a href="javascript:;">
                        <span>{{ l('ChangeTexts') }}</span>
                      </a>
                    </a-menu-item>
                    <a-menu-item
                      v-if="isGranted('Pages.Administration.Languages.Edit')"
                      @click="setAsDefaultLanguage(record)"
                    >
                      <a href="javascript:;">
                        <span>{{ l('SetAsDefaultLanguage') }}</span>
                      </a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import {
    PagedListingComponentBase,
    IPagedRequestDto,
    IPagedResultDto,
  } from '/@/shared/component-base';
  import CreateOrEditLanguage from './create-or-edit-languages/create-or-edit-languages.vue';
  import { defineComponent } from 'vue';
  import _ from 'lodash';
  import {
    LanguageListDto,
    SetDefaultLanguageInput,
    LanguageServiceProxy,
  } from '/@/shared/service-proxies/service-proxies';
  import {
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
  } from '@ant-design/icons-vue';
  import { ColumnType } from 'ant-design-vue/lib/table';

  export default defineComponent({
    name: 'languages',
    mixins: [PagedListingComponentBase],
    components: {
      CreateOrEditLanguage,
      CheckCircleTwoTone,
      CloseCircleTwoTone,
      PlusOutlined,
      DeleteOutlined,
      EditOutlined,
    },
    data() {
      return {
        languageServiceProxy: new LanguageServiceProxy(),
        tenantId: new Number(),
        defaultLanguageName: '',
      };
    },
    created() {
      this.tenantId = this.appSession.tenantId;
    },
    methods: {
      /**
       * table默认配置 （是否禁用）
       */
      getCheckboxProps(record) {
        return {
          disabled: record.displayName == '中文（简体）' || record.displayName == '英语',
          name: record.displayName,
        };
      },
      /** 获取数据 */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this.languageServiceProxy
          .getLanguages()
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.defaultLanguageName = res.defaultLanguageName as any;
            const resData: IPagedResultDto = {
              items: res.items,
              totalCount: res.items?.length as number,
            };
            this.showPaging(resData);
          });
      },
      getColumns(): ColumnType<LanguageListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('Name'),
            dataIndex: 'displayName',
            ellipsis: true,
            key: 'displayName',
          },
          {
            title: this.l('Code'),
            dataIndex: 'name',
            ellipsis: true,
            key: 'name',
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'creationTime',
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
            key: 'creationTime',
          },
          {
            title: this.l('Enabled'),
            dataIndex: 'isDisabled',
            ellipsis: true,
            align: 'center',
            key: 'isDisabled',
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            ellipsis: true,
            fixed: 'right',
            width: 250,
            key: 'actions',
          },
        ];
      },
      /**
       * 创建编辑语言
       */
      createOrEditLanguage(item?: LanguageListDto) {
        this.modalHelper
          .create(
            CreateOrEditLanguage,
            { id: item?.id },
            {
              width: '400px',
            },
          )
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
      /**
       * 批量删除
       */
      batchDelete(_e) {
        const selectCount = this.selectedRowKeys.length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', selectCount),
          '',
          (res) => {
            if (res) {
              const ids = _.map(this.selectedRowKeys);
              this.isTableLoading = true;
              this.languageServiceProxy
                .batchDelete(ids)
                .finally(() => {
                  this.isTableLoading = false;
                })
                .then(() => {
                  this.refresh();
                  this.notify.success(this.l('SuccessfullyDeleted'));
                });
            }
          },
        );
      },
      /**
       * 单个删除
       */
      deleteItem(item: LanguageListDto) {
        this.isTableLoading = true;
        this.languageServiceProxy
          .deleteLanguage(item.id)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.refresh();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      },
      /**
       * 设为默认语言
       */
      setAsDefaultLanguage(item: LanguageListDto) {
        this.isTableLoading = true;
        let setdefault: SetDefaultLanguageInput = new SetDefaultLanguageInput();
        setdefault.name = item.name as any;
        this.languageServiceProxy
          .setDefaultLanguage(setdefault)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.refresh();
            this.notify.success(this.l('SettingSuccessfully'));
          });
      },
      /**
       * 更换文本
       */
      changeTexts(item: LanguageListDto) {
        setTimeout(() => {
          this.$router.push({
            path: '/system/language-texts',
            query: { lang: item.name },
          });
        }, 300);
      },
    },
  });
</script>

<style scoped lang="less">
  .subscriptionEndUtc {
    text-align: center;
  }

  // table
  .list-table {
    i {
      margin-right: 10px;
    }
  }

  .table-edit {
    .anticon {
      margin-right: 10px;
    }
  }

  .table-delete,
  .ant-dropdown-link {
    margin-left: 20px;
  }
</style>
